<?php

namespace App\Services;


use App\Models\Student;
use App\Models\User;

/**
 * 用户 Service
 *
 * Class BqrzService
 * @package App\Services
 */
class UserService
{

    public function __construct()
    {
    }

    protected function findUser($id)
    {
        return User::findOrFail($id);
    }

    public function registerUser(array $data)
    {
        $mobile = $data['mobile'];
        $password = $data['password'];
        $userModel = User::query()->where('mobile', $mobile)->first();
        $student = Student::query()->where('mobile', $mobile)->first();
        if ($userModel) {
            throw  new \Exception('该手机号已注册为培优策账户,可直接登录');
        } else if (!$student) {
            throw  new \Exception('您的身份有误，不能注册');
        } else {
            $user = $this->createUser([
                'mobile' => $mobile,
                'password' => bcrypt($password),
                'student_id'=>$student->id
            ]);
            return $user;
        }
    }


    /**
     * 创建创意星球用户
     *
     * @param array $data
     * @throws \Exception
     *
     * @return User
     */
    public function createUser(array $data)
    {
        $mobile = $data['mobile'];
        $password = $data['password'];
        $student_id = $data['student_id'];
        \DB::beginTransaction();
        try {
            $user = User::create([
                'mobile' => $mobile,
                'password' => $password,
                'type' => 'student',
                'student_id'=> $student_id
            ]);
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw $e;
        }
        return $user;
    }
}
